﻿using AdvancedTool.Standard;
using ParkSaleForAdmin.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Json;
using System.Windows;
using System.Xml.Serialization;

namespace ParkSaleForAdmin
{
    public class DataToUIAttribute : Attribute
    {
        /// <summary>
        /// 数据索引名称
        /// </summary>
        public string Value
        {
            get;
            set;
        }
        /// <summary>
        /// 呈现标题名称
        /// </summary>
        public string Title
        {
            get;
            set;
        }
        /// <summary>
        /// 可编辑性
        /// </summary>
        public bool Editable
        {
            get;
            set;
        }
        public DataToUIAttribute(string title, string value, bool editalbe = true)
        {
            Title = title;
            Value = value;
            Editable = editalbe;
        }
        public DataToUIAttribute(string title, bool editalbe = true)
        {
            Title = title;
            Value = null;
            Editable = editalbe;
        }
    }

    [Serializable]
    public class Setting
    {
        public string API
        {
            get;
            set;
        }
    }

    public class SystemManager
    {
        static Setting setting = new Setting() { API = "https://localhost:44338/" };
        public static string Location = "API_Setting.setting";
        public static void InitSystem()
        {

            {
                XmlSerializer formatter = new XmlSerializer(typeof(Setting));
                if (!File.Exists(Location))
                {
                    using (var stream = new FileStream(Location, FileMode.Create, FileAccess.ReadWrite))
                    {

                        formatter.Serialize(stream, setting);
                    }
                }
                else
                {
                    try
                    {
                        using (var stream = new FileStream(Location, FileMode.Open, FileAccess.ReadWrite))
                        {
                            Setting i = (Setting)formatter.Deserialize(stream);
                            if (i.API != null)
                            {
                                if (i.API.Length > 0)
                                    setting = i;
                            }
                        }


                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }


                }
            }

        }
        public static string API
        {
            get => setting.API + "/Su";
        }
        public static string Address
        {
            get => setting.API;
        }
        public static string Admin = "IAMtheKing";

        public static HttpClient Http = new HttpClient();
        public static void Request<TResponse>(int signal, string[] requests, string token, AsyncTask.ResultAction result, AsyncTask.PreAction pre = null)
        {
            AsyncTask t = new AsyncTask();
            t.Run(delegate ()
            {
                //try
                //{
                    var task = SystemManager.Http.PostAsync(API, JsonContent.Create<SuUserRequestInfo>(new Data.SuUserRequestInfo() { RequestSignal = signal, Token = token, RequestArg = requests }));
                    task.Wait();
                    var deal = task.Result.Content.ReadFromJsonAsync<SuUserResponseInfo<TResponse>>();
                    deal.Wait();
                    task.Dispose();
                    object body = deal.Result.Body;
                    deal.Dispose();

                    return body;
                //}
                //catch (Exception ex)
                //{
                //    return null;
                //}

            }, result, pre);
        }

        public static void Request<T>(int signal, AsyncTask.ResultAction result, AsyncTask.PreAction pre, params string[] requestargs)
        {
            Request<T>(signal, requestargs, Admin, result, pre);
        }

    }
    public class AsyncTask : AsyncTasking<Object>
    {
        public delegate Object BackGroundAction();
        /// <summary>
        /// 预处理方法
        /// </summary>
        /// <param name="self"></param>
        public delegate void PreAction();
        /// <summary>
        /// 结果处理方法
        /// </summary>
        /// <param name="result"></param>
        /// <param name="self"></param>
        public delegate void ResultAction(Object result);

        BackGroundAction main;
        PreAction pre;
        ResultAction result;

        protected override void PreInit()
        {
            if (pre != null)
                pre();
        }

        protected override Object BackgroundTask()
        {
            return main();
        }
        protected override void PostResult(Object result, AsyncTasking<Object> self)
        {

            this.result(result);
        }

        public void Run(BackGroundAction backGround, ResultAction result, PreAction pre = null)
        {
            if (backGround == null)
            {
                throw new Exception("后台任务不可为空");
            }
            if (result == null)
            {
                throw new Exception("结果处理任务不能为空");
            }
            this.main = backGround;
            this.result = result;
            this.pre = pre;
            this.InvokeAsync();
        }
    }

    namespace Data
    {

        public sealed class SQLHelpler
        {
            public static string MakeSelectStr(string table, string targetkey, string targetvalue)
            {
                return $"SELECT `{table}`.* FROM `{table}` WHERE `{table}`.`{targetkey}` = '{targetvalue}'; ";
            }
            public static string MakeSelectStr(string table, string condition)
            {
                return $"SELECT `{table}`.* FROM `{table}` {condition}; ";
            }
        }
        [Serializable]
        public class RowData
        {
            public string Name
            {
                get;
                set;
            }
            public string Value
            {
                get;
                set;
            }
        }
        [Serializable]
        public class DatabaseData
        {

            public RowData this[string name]
            {
                get
                {
                    return Detail.Find(delegate (RowData data)
                     {
                         return data.Name.Equals(name);
                     }
                      );
                }
            }
            public List<RowData> Detail
            {
                get;
                set;
            }
        }
        [Serializable]
        public class SuUserRequestInfo
        {
            public const int s_ChangeValue = 1001, s_AppendValue = 1002, s_DeleteValue = 1003, s_MessageSend = 1004, s_FindValue = 1000, s_Auth = 999, s_Random = 1005;

            public int RequestSignal
            {
                get;
                set;
            }
            public string[] RequestArg
            {
                get;
                set;
            }
            public string Token
            {
                get;
                set;
            }
        }
        [Serializable]
        public class SuUserResponseInfo<T>
        {
            public const int s_Error = -1000, s_BadToken = -1001, OK = 1, s_BadArgs = -1002, s_WrongSignal = -1003;
            public T Body
            {
                get;
                set;
            }
            public int ResponseSignal
            {
                get;
                set;
            }
        }
    }
}
